<?php include_once('database.php'); 

session_start();
$_SESSION["H7_Library_Message"]= "";

if($_GET["action"]=="delete"){
	$db -> query("DELETE FROM media WHERE MediaId =".$_GET["id"]);
	$db -> query("UPDATE item 
				  SET MediaId = 0
				  WHERE MediaId =".$_GET["id"]);
	header('Location:'.$_SERVER['HTTP_REFERER']);
	die;	
}

$counter = 0;

foreach($_POST["MediaName"] as $value){
	$value = trim($value);
    $value = mysqli_real_escape_string($db,$value);
	if($value == "" || $value == NULL){
		$_SESSION["H7_Library_Message"].="Prøvede at lave et medie uden tekst".'<br>';
	}else{
		//Checking for dublicate and if a change was made in this field when submitted.
		if(isset($_POST["MediaId"])){
			$change = $db->query("SELECT * 
								   FROM media 
								   WHERE MediaName ='".$value."'
								   AND MediaId =".$_POST["MediaId"][$counter].";");
			$exist = $change->num_rows;
			
			if($exist>0){
				goto counter;
			}
			
			$query = mysql_query("SELECT * 
								   FROM media 
								   WHERE MediaName ='".$value."'
								   AND MediaId !=".$_POST["MediaId"][$counter].";");

		}else{
			$query = mysql_query("SELECT * 
								   FROM media 
								   WHERE MediaName ='".$value."';");
		}
		$dub = $db -> query($query);
		$exist =$dub -> num_rows;
		
		if($exist > 0){
		    $_SESSION["H7_Library_Message"].="Et andet medie existere allerede med navnet: ".htmlspecialchars($value).'<br>';			
		}else{
			if($_GET["action"]=="create"){
                $db->query("INSERT INTO media (MediaName)
                             VALUES ('".$value."');");
                $_SESSION["H7_Library_Message"].="Medie oprettet: ".htmlspecialchars($value).'<br>';
            }
            if($_GET["action"]=="edit"){
                $db ->query("UPDATE media
                            SET MediaName = '".$value."'
                            WHERE MediaID=".$_POST["MediaId"][$counter].";");
                $_SESSION["H7_Library_Message"].="Medie navn ændret til: ".htmlspecialchars($value).'<br>';
            }			
		}
	}
	counter:
	$counter ++;
	
}	
header('Location:'.$_SERVER['HTTP_REFERER']);

?>